<template>
  <div class="admin">
    <el-card class="box-card" v-if="status === 'index'">
      <el-row>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="getData"
          v-if="has('banners/index')"
          >刷新</el-button
        >
        <el-button
          type="info"
          icon="el-icon-refresh"
          size="mini"
          @click="reset"
          v-if="has('banners/index')"
          >重置</el-button
        >
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="add"
          v-if="has('banners/store')"
          >添加</el-button
        >
      </el-row>
      <el-table
        :data="data.data"
        v-loading="table_loading"
        row-key="id"
        style="width: 100%;margin:10px auto"
        size="mini"
        :header-cell-style="{ background: '#f3f8fe', color: '#333' }"
      >
        <el-table-column
          fixed
          prop="id"
          label="ID"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="url"
          label="链接"
          align="center"
        ></el-table-column>

        <el-table-column
          prop="start_time"
          label="开始时间"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="end_time"
          label="结束时间"
          align="center"
        ></el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template slot-scope="scope">
            <span :style="statusArr[scope.row.status].style">{{
              statusArr[scope.row.status].title
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="image" label="图片" width="200" align="center">
          <template slot-scope="scope">
            <el-image
              :src="scope.row.image"
              :style="{ width: '100px', height: '100px' }"
              :preview-src-list="[scope.row.image]"
              fit="contain"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column
          prop="created_at"
          label="创建时间"
          align="center"
          sortable
        ></el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="edit(scope.row.id)"
              v-if="has('banners/show')"
            ></el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="del(scope.row.id, scope.$index)"
              v-if="has('banners/destroy')"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        style="text-align:center;margin:20px 0;"
        :current-page="searchParams.page"
        :page-sizes="pageSizes"
        layout="total,prev, pager, next,sizes"
        :total="data.total"
        @size-change="changeSize"
        @current-change="changePage"
      ></el-pagination>
    </el-card>

    <!-- 添加 -->
    <el-card v-if="status === 'add'">
      <div slot="header">
        <el-page-header @back="init" content="添加轮播"></el-page-header>
      </div>
      <el-form
        ref="form"
        :rules="rules"
        :model="editParams"
        label-width="120px"
        :style="{ width: '90%', margin: '0 auto' }"
      >
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="editParams.title"
            placeholder="请输入标题"
          ></el-input>
        </el-form-item>
        <el-form-item label="链接">
          <el-input
            v-model="editParams.url"
            placeholder="请输入跳转链接"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editParams.status" placeholder="请选择状态">
            <el-option
              v-for="item in statusArr"
              :key="item.id"
              :value="item.id"
              :label="item.title"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <el-button
            size="mini"
            type="primary"
            @click="openImage(2, false, extra)"
            >选择图片</el-button
          >
          <div>
            <el-image
              v-if="editParams.image"
              :src="editParams.image"
              :preview-src-list="[editParams.image]"
              style="height: 200px"
              fit="contain"
            >
            </el-image>
          </div>
        </el-form-item>
        <el-form-item label="生效方式" prop="show_type">
          <el-radio-group v-model="editParams.show_type">
            <el-radio v-for="item in typeArr" :label="item.id" :key="item.id">{{
              item.title
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="显示时间" v-if="editParams.show_type == 2">
          <el-date-picker
            v-model="dateRanger"
            type="datetimerange"
            value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit('form', 1)">保 存</el-button>
          <el-button @click="init">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card v-if="status === 'edit'">
      <div slot="header">
        <el-page-header @back="init" content="编辑轮播"></el-page-header>
      </div>
      <el-form
        ref="form"
        :rules="rules"
        :model="editParams"
        label-width="120px"
        :style="{ width: '90%', margin: '0 auto' }"
      >
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="editParams.title"
            placeholder="请输入标题"
          ></el-input>
        </el-form-item>
        <el-form-item label="链接">
          <el-input
            v-model="editParams.url"
            placeholder="请输入跳转链接"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editParams.status" placeholder="请选择状态">
            <el-option
              v-for="item in statusArr"
              :key="item.id"
              :value="item.id"
              :label="item.title"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <el-button
            size="mini"
            type="primary"
            @click="openImage(2, false, extra)"
            >选择图片</el-button
          >
          <div>
            <el-image
              v-if="editParams.image"
              :src="editParams.image"
              :preview-src-list="[editParams.image]"
              style="height: 200px"
              fit="contain"
            >
            </el-image>
          </div>
        </el-form-item>
        <el-form-item label="生效方式" prop="show_type">
          <el-radio-group v-model="editParams.show_type">
            <el-radio v-for="item in typeArr" :label="item.id" :key="item.id">{{
              item.title
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="显示时间" v-if="editParams.show_type == 2">
          <el-date-picker
            v-model="dateRanger"
            type="datetimerange"
            value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit('form', 2)">保 存</el-button>
          <el-button @click="init">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <SimpleImageUpload
      :cardStatus="cardStatus"
      :imageFormatArr="imageFormatArr"
      :imageData="imageData"
      :imageLoading="imageLoading"
      :uploadImageAction="uploadImageUrl"
      :multiple="multiple"
      @uploadImageSuccess="uploadFileSuccess"
      @uploadImageBefore="uploadImageBefore"
      @changeImageSize="changeImageSize"
      @changeImagePage="changeImagePage"
      @changeImageFormat="changeImageFormat"
      @choiceImageConfirm="choiceImageConfirm"
      @closeImage="closeImage"
      @getImages="getImages"
    ></SimpleImageUpload>
  </div>
</template>

<script>
import api from "../../api/api.js";
import SimpleImageUpload from "@/components/SimpleImageUpload/index.vue";
export default {
  name: "banners",
  components: {
    SimpleImageUpload
  },
  data() {
    return {
      status: "index", // 页面控制
      dateRanger: "",
      data: [], // 表格诗句
      table_loading: true, // 表格加载中
      loading: false, //全局加载中
      imageStatus: false,
      addStatus: false,
      editStatus: false,
      statusArr: [
        { id: 0, title: "隐藏", style: { color: "red" } },
        { id: 1, title: "显示", style: { color: "green" } }
      ],
      typeArr: [
        { id: 1, title: "立即生效" },
        { id: 2, title: "按时间生效" }
      ],
      uploadUrl: "/admin/common/upload?format=3", // 上传地址
      pageSizes: [10, 20, 50, 100, 200, 500, 800, 1000, 2000], // 每页条数默认10
      searchParams: {
        // 搜索参数
        page: 1,
        limit: 10
      },
      editParams: {
        image: "",
        status: "",
        show_type: "",
        start_time: "",
        end_time: "",
        url: ""
      },
      rules: {
        // 验证规则
        status: [{ required: true, message: "请选择状态", trigger: "change" }],
        title: [{ required: true, message: "请输入标题", trigger: "change" }],
        image: [{ required: true, message: "请上传图片", trigger: "change" }],
        show_type: [
          { required: true, message: "请选择生效方式", trigger: "change" }
        ]
      },
      cardStatus: false,
      imageFormatArr: [
        { id: "", title: "全部" },
        { id: 1, title: "商品图片" },
        { id: 2, title: "商品详情图" },
        { id: 3, title: "banner" },
        { id: 4, title: "活动" },
        { id: 5, title: "盲盒" }
      ],
      imageData: {},
      imageLoading: false,
      uploadImageUrl: "/admin/common/upload?format=3",
      multiple: false,
      scene: 1, // 打开组件场景
      extra: {}
    };
  },
  created() {
    this.getData();
  },

  methods: {
    // 查看大图
    bigImage(url) {
      this.$alert("图片", {
        message: "<img  src=" + url + " style='height:200px;width:200px'>",
        dangerouslyUseHTMLString: true
      });
    },
    // 加载中
    load() {
      this.loading = this.$loading({
        lock: true,
        text: "数据加载中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
    },

    // 取消加载
    unload() {
      this.loading.close();
    },
    uploadImageBefore() {
      this.load();
    },
    closeImage() {
      this.cardStatus = false;
    },
    // 改变图片组件每页条数时
    changeImageSize(limit) {
      this.imageParams.limit = limit;
      this.getImages();
    },
    // 改变图片组件当前页码时
    changeImagePage(page) {
      this.imageParams.page = page;
      this.getImages();
    },
    // 打开组件图片
    openImage(scene, multiple, extra) {
      this.multiple = multiple; // 单选还是多选
      this.scene = scene;
      this.extra = extra; // 额外数据
      this.cardStatus = true;
      this.getImages();
    },
    // 组件确定选择图片
    choiceImageConfirm(choiceImages) {
      if (this.scene == 1) {
        this.editParams.goods_images = this.editParams.goods_images.concat(
          choiceImages
        );
      } else if (this.scene == 2) {
        this.editParams.image = choiceImages[0];
      } else if (this.scene == 3) {
        this.extra.row.image = choiceImages[0];
      } else if (this.scene == 4) {
        var html = "";
        choiceImages.map(item => {
          html += `<div><img src="${item}" /></div>`;
        });
        this.setHtml(html);
        console.log("html:", html);
      }
    },
    // 组件图片上传成功取消遮罩重新请求数据
    uploadFileSuccess(res) {
      this.unload();
      this.getImages();
      this.$message.success(res.msg);
    },
    // 选择类型筛选图片
    changeImageFormat(type) {
      this.initImage(type);
      this.getImages();
    },
    // 查看图片
    getImages() {
      this.cardStatus = true;
      this.imageLoading = true;
      api.images
        .index({ params: this.imageParams })
        .then(res => {
          this.imageLoading = false;
          if (res.data.code == 200) {
            this.imageData = res.data.data;
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 重置图片搜索参数
    initImage(type) {
      this.imageParams.format = type;
      this.imageParams.page = 1;
    },
    // 获取所有分类
    getData() {
      this.table_loading = true;
      api.banners
        .index({ params: this.searchParams })
        .then(res => {
          if (res.data.code === 200) {
            this.table_loading = false;
            this.data = res.data.data;
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 重置搜索参数重新搜索
    reset() {
      this.init();
      this.getData();
    },
    // 初始化
    init() {
      this.editParams = {
        type: "",
        status: ""
      };
      this.addStatus = false;
      this.editStatus = false;
      this.imageStatus = false;
      this.status = "index";
    },
    // 改变每页条数时
    changeSize(limit) {
      this.searchParams.limit = limit;
      this.getData();
    },
    // 改变当前页码时
    changePage(page) {
      this.searchParams.page = page;
      this.getData();
    },
    // 添加页面
    add() {
      this.status = "add";
    },
    // 编辑页面
    edit(id) {
      this.load();
      api.banners
        .show(id)
        .then(res => {
          this.unload();
          if (res.data.code === 200) {
            this.status = "edit";
            this.editParams = res.data.data;

            if (this.editParams.show_type == 2) {
              this.dateRanger = [
                this.editParams.start_time,
                this.editParams.end_time
              ];
            }
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 保存添加或编辑
    submit(formName, type) {
      this.$refs[formName].validate((valid, error) => {
        if (valid) {
          if (this.editParams.show_type == 2) {
            if (!this.dateRanger) {
              this.$message.error("请选择时间范围");
              return;
            } else {
              this.editParams.start_time = this.dateRanger[0];
              this.editParams.end_time = this.dateRanger[1];
            }
          }

          this.load();
          // 添加
          if (type === 1) {
            api.banners
              .store(this.editParams)
              .then(res => {
                this.unload();
                if (res.data.code === 200) {
                  this.reset();
                }
              })
              .catch(error => {
                console.log(error);
              });
          } else if (type === 2) {
            // 编辑
            api.banners
              .edit(this.editParams.id, this.editParams)
              .then(res => {
                this.unload();
                if (res.data.code === 200) {
                  this.reset();
                }
              })
              .catch(error => {
                console.log(error);
              });
          }
        } else {
          this.$message.error(Object.values(error)[0][0].message);
          return false;
        }
      });
    },
    // 删除
    del(id, index) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        type: "warning"
      })
        .then(() => {
          api.banners
            .del(id)
            .then(res => {
              if (res.data.code === 200) {
                this.$message({
                  type: "success",
                  message: "删除成功!"
                });
                this.data.data.splice(index, 1);
                this.data.total--;
              }
            })
            .catch(error => {
              console.log(error);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    }
  }
};
</script>

<style scoped lang="less">
.admin {
  margin: 0 auto;
  .search {
    margin: 0 auto 10px auto;
  }
}
</style>
